package dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bean.User;
import dao.UserDao;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	@Override
	public boolean addUser(User user) {
		this.getSessionFactory().getCurrentSession().save(user);
		return true;
	}

	@Override
	public boolean modifyUser(User user) {
		// TODO Auto-generated method stub
		this.getSessionFactory().getCurrentSession().update(user);
		return true;
	}

	@Override
	public boolean deleteUser(User user) {
		// TODO Auto-generated method stub
		this.getSessionFactory().getCurrentSession().delete(user);
		return true;
	}

	@Override
	public User findUser(User user) {
		List l=this.getSessionFactory().getCurrentSession().createCriteria(User.class).add(Restrictions.eq("username", user.getUsername())).add(Restrictions.eq("password", user.getPassword())).list();
		if(l.size()==0){
			return null;
		}
		else{
			return (User) l.get(0);
			}
	}

	@Override
	public User findUserByUsername(String username) {
		List l=this.getSessionFactory().getCurrentSession().createCriteria(User.class).add(Restrictions.eq("username", username)).list();
		if(l.size()==0)
			return null;
		else
			return (User) l.get(0);
	}

	@Override
	public User findUserById(int id) {
		Object o=this.getSessionFactory().getCurrentSession().load(User.class, id);
		if(o==null)
			return null;
		else
			return (User) o;
	}

	@Override
	public List findRecentUsers() {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().find("from User u where u.id>0 order by id desc");
		if(l.size()>5)
			return l.subList(0, 5);
		else
			return l;
	}

	@Override
	public List findUserByName(String name) {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().createCriteria(User.class).add(Restrictions.like("name", "%"+name+"%")).list();
		return l;
	}

}
